<template>
  <el-input-number style="width: 100%" v-if="auth === 'edit'" :min="min" :max="max" v-model="model"
                   :class="wrapperClass"
                   :placeholder="placeholder" @blur="fieldValueChange"/>

  <el-input-number style="width: 100%" v-else-if="auth === 'browse'" v-model="model" disabled
                   @blur="fieldValueChange"/>

  <el-input-number style="width: 100%" v-else-if="auth === 'hide'" v-model="model" disabled
                   type="password" @blur="fieldValueChange"/>

  <el-text truncated v-else-if="auth === 'static'">
    {{ model }}
  </el-text>
</template>
<script setup>
import {computed, defineProps, ref, unref} from 'vue';
import {DefaultFieldDefinition} from '@/components/form/DefaultFormDefinition';
import {isEmpty} from '@/utils/CommonUtils';
import './textInput.css';

const props = defineProps({
  auth: {
    type: String,
    default: 'static'
  },
  notNull: {
    type: String,
    default: '0' //0表示非必填, 1表示必填
  },
  field: {
    type: Object,
    default() {
      return DefaultFieldDefinition;
    }
  }
});
const model = ref();
const emits = defineEmits(['fieldValueChange']);

function getFieldValue(rowData) {
  return unref(model);
}

function resetField() {
  model.value = undefined;
}

function setFieldValue(value, obj) {
  if (isEmpty(value)) {
    model.value = undefined;
    return;
  }
  try {
    model.value = parseInt(value + '');
  } catch (e) {
  }
}

function fieldValueChange() {
  emits('fieldValueChange', props.field);
}

function getFieldValueText() {
  return unref(model);
}

const min = computed(() => {
  if (isEmpty(props.field)) {
    return undefined;
  }
  return props.field.valueMin;
});

const max = computed(() => {
  if (isEmpty(props.field)) {
    return undefined;
  }
  return props.field.valueMax;
});

function getFieldValueWithCheck(rowData) {
  if (props.notNull + '' === '1' && isEmpty(model.value)) {
    throw new Error('请将必填项填写完整');
  }
  return model.value;
}

const placeholder = computed(() => {
  if (isEmpty(props.field.id)) return '';
  return `请输入${props.field.alias ? props.field.alias : props.field.showName}`;
});

const wrapperClass = computed(() => {
  return {
    notNull: props.notNull === '1' && isEmpty(model.value)
  };
});

defineExpose({
  getFieldValue,
  setFieldValue,
  resetField,
  getFieldValueText,
  getFieldValueWithCheck,
});
</script>
